import "dart:convert";
import "dart:io";

import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/apartment/api.dart";
import "package:ct_pa_majordomo/pages/apartment/check_in/widget/cohabitant/index.dart";
import "package:ct_pa_majordomo/pages/apartment/check_in/widget/rent_info/index.dart";
import "package:ct_pa_majordomo/pages/apartment/edit_remark/index.dart";
import "package:ct_pa_majordomo/pages/commonApi.dart";
import "package:ct_pa_majordomo/pages/pre_check_in/api.dart";
import "package:ct_pa_majordomo/pages/widgets/menu_block.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/state/common.dart";
import "package:ct_pa_majordomo/utils/common.dart";
import "package:ct_pa_majordomo/utils/date_tools.dart";
import "package:ct_pa_majordomo/utils/form_validator.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/utils/storage.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:ct_pa_majordomo/widgets/show_datetime_picker.dart";
import "package:ct_pa_majordomo/widgets/wrap_item.dart";
import "package:dio/dio.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:image_picker/image_picker.dart";
import "package:provider/provider.dart";

class PreCheckInCheckIn extends StatefulWidget {
  final Map room;
  final int registerId;
  const PreCheckInCheckIn({super.key, required this.room, required this.registerId});

  @override
  State<StatefulWidget> createState() => _PreCheckInCheckInState();
}

class _PreCheckInCheckInState extends State<PreCheckInCheckIn> {
  int? _apartmentId;
  final Text _required =
  const Text("*", style: TextStyle(color: ThemeVars.colorError));
  final List _dateList = ["1月", "3月", "6月", "1年"];
  int _dateCheckIndex = -1;
  Map _params = {
    "checkInStart": DateTools.formatTime(DateTime.now().millisecondsSinceEpoch, format: "{y}-{m}-{d}"),
    "checkInEnd": DateTools.formatTime(DateTime.now().millisecondsSinceEpoch, format: "{y}-{m}-{d}"),
    "rentObject": {},
    "remark": "",
  };

  String _formatDate(DateTime date) {
    return DateTools.formatTime(date.millisecondsSinceEpoch, format: "{y}-{m}-{d}");
  }

  void _submit() async {
    Map<String, dynamic> data = {
      ..._params,
      "apartmentId": _apartmentId,
      "roomId": widget.room["roomId"],
      "registerId": widget.registerId,
    };
    await preCheckInApi.assignRoom(data);
    EasyLoading.showSuccess("办理成功");
    if (context.mounted) {
      Stacker.pop(true);
    }
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // final Map? apartment = Provider.of<CommonState>(context).apartment;
    final Map? apartment = jsonDecode(storage.getString("apartment") ?? "");
    _apartmentId = apartment?["apartmentId"];
    return NormalScaffold(
      title: "办理入住",
      child: ListView(
        children: [
          Container(
            padding: const EdgeInsets.all(ThemeVars.paddingPage),
            decoration: const BoxDecoration(
              color: Colors.white,
            ),
            child: Text(widget.room["name"]),
          ),
          const SizedBox(height: 12,),
          MenuBlock(
            title: Text("入住周期"),
            content: Wrap(
                spacing: 12,
                children: List.generate(_dateList.length, (index) {
                  return WrapItem(
                      span: 3,
                      child: SizedBox(
                        height: 24,
                        child: Button(
                          type: _dateCheckIndex == index ? ButtonType.primaryLight : ButtonType.primaryOutline,
                          onPressed: () {
                            setState(() {
                              _dateCheckIndex = index;
                              int month = 0;
                              switch(index) {
                                case 0:
                                  month = 1;
                                  break;
                                case 1:
                                  month = 3;
                                  break;
                                case 2:
                                  month = 6;
                                  break;
                                case 3:
                                  month = 12;
                                  break;
                              }
                              DateTime date = DateTime.parse(_params["checkInStart"]);
                              DateTime futureDate =  DateTime(date.year, date.month + month, date.day - 1);
                              print("时间：》》》》${_formatDate(futureDate)}");
                              _params["checkInEnd"] = _formatDate(DateUtils.addDaysToDate(futureDate, -1));
                            });
                          },
                          child: Text(_dateList[index], textAlign: TextAlign.center, style: TextStyle(fontSize: 12),),
                        ),
                      )
                  );
                })
            ),
            items: [
              MenuBlockItem(
                  text: "开始时间",
                  prefix: _required,
                  suffix: Text(_params["checkInStart"].toString()),
                  onTap: () {
                    showDatetimePicker(
                      context: context,
                      initialDateTime: DateTime.now(),
                      onchange: (value) => setState(() {
                        _params["checkInStart"] = DateTools.formatTime(value.millisecondsSinceEpoch, format: "{y}-{m}-{d}");
                      }),
                    );
                  }
              ),
              MenuBlockItem(
                  text: "结束时间",
                  prefix: _required,
                  suffix: Text(_params["checkInEnd"].toString()),
                  onTap: () {
                    showDatetimePicker(
                      context: context,
                      initialDateTime: DateTime.now(),
                      onchange: (value) => setState(() {
                        _params["checkInEnd"] = DateTools.formatTime(value.millisecondsSinceEpoch, format: "{y}-{m}-{d}");
                      }),
                    );
                  }
              ),
              MenuBlockItem(
                  text: "房租信息",
                  prefix: _required,
                  suffix: Text(_params["rentObject"].isEmpty ?  "请填写" : "已填写", style: TextStyle(color: ThemeVars.colorTextSec, fontSize: 14),),
                  onTap: () {
                    Navigator.push(context, CupertinoPageRoute(builder: (BuildContext context) {
                      return RentInfo(
                          rentObject: _params["rentObject"],
                          changeInfo: (value) {
                            setState(() {
                              _params["rentObject"] = value;
                            });
                          });
                    }));
                  }
              ),
              MenuBlockItem(
                text: "备注",
                suffix: Text(_params["remark"].isNotEmpty ? "已填写" : "请填写", style: TextStyle(fontSize: 14, color: ThemeVars.colorTextSec),),
                onTap: () {
                  Navigator.push(context, CupertinoPageRoute(builder: (BuildContext context) {
                    return EditRemark(remark: _params["remark"]);
                  })).then((remark) {
                    if (remark != null) {
                      setState(() {
                        _params["remark"] = remark;
                      });
                    }
                  });
                }
              )
            ],
          ),
          Padding(
            padding: EdgeInsets.fromLTRB(ThemeVars.paddingPage, 50, ThemeVars.paddingPage, 30),
            child: Button(
                onPressed: () async {
                  _submit();
                },
                child: Text("确定")
            ),
          )
        ],
      ),
    );
  }

}